<template>
    <van-nav-bar title="邮箱认证" left-text="" left-arrow @click-left="goBack" />
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="LoginUser.email" name="email" label="邮箱" placeholder="请输入邮箱" readonly
                :rules="[{ required: true, message: '请填写邮箱' }]" />
            <van-field v-model="code" center clearable name="code" label="邮箱验证码" placeholder="请输入邮箱验证码"
                :rules="[{ required: true, message: '请填写邮箱验证码' }]">
                <template #button>
                    <van-button size="small" type="primary" :disabled="status" @click="send">
                        <span v-if="!status">发送验证码</span>
                        <van-count-down v-show="status" ref="countDown" :time="60000" format="ss秒" @finish="onFinish" />
                    </van-button>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>
<script setup>
const goBack = () => {
    history.back();
};
const router = useRouter();
const { cookies } = useCookies();
const LoginUser = reactive(cookies.get("LoginUser") ?? {});
const code = ref("");
const status = ref(false);
const countDown = ref(null);
const onSubmit = async () => {
    let result = await Api.email({
        busid: LoginUser.id,
        email: LoginUser.email,
        code: code.value,
    });
    if(result.code == 1){
        showSuccessToast({
            message: result.msg,
            onClose: () => {
                router.push("/business/base/index");
            }
        })
    }else{
        showFailToast(result.msg);
    }
};
const send = async () => {
    status.value = true;
    // 倒计时开始
    countDown.value.start();
    let result = await Api.sendmail({
        busid: LoginUser.id,
        email: LoginUser.email,
    });
    if (result.code == 1) {
        showSuccessToast(result.msg);
    } else {
        showFailToast(result.msg);
    }
};
// 倒计时结束触发
const onFinish = () => {
    countDown.value.reset();
    status.value = false;
};
</script>